package com.li.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.li.domain.SystemAddress;
import com.li.domain.UploadFile;
import com.li.domain.User;
import com.li.domain.UserRole;
import com.li.domain.model.UserModel;
import com.li.exception.NotFondException;
import com.li.mapper.UploadFileMapper;
import com.li.mapper.UserMapper;
import com.li.mapper.UserRoleMapper;
import com.li.service.SystemAddressService;
import com.li.service.UserService;
import com.li.utlis.CommonUtil;
import com.li.utlis.EasyExcelUtil;
import com.li.utlis.FilePathUtil;
import com.li.utlis.FileUploadUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private UploadFileMapper uploadFileMapper;

    @Autowired
    private SystemAddressService systemAddressService;

    @Override
    public List<User> listQueryUser(User user,Integer page,Integer limit) {
        Integer index=(page-1)*limit;
        return userMapper.listQueryUser(user,index,limit);
    }

    @Override
    public Integer listQueryUserCount(User user) {
        return userMapper.listQueryUserCount(user);
    }

    @Transactional
    @Override
    public String addUser(User user) {
        if (user==null){
            throw new NotFondException("用户为空");
        }else{
            user.setCreateTime(new Date());
            //设置用户id
            String userId=UUID.randomUUID().toString();
            user.setId(userId);
            //将用户存放到表中
            userMapper.insert(user);
            //获取角色id
            if (user.getRoleIds()!=null && user.getRoleIds().length>0){
                for (Integer rId:user.getRoleIds()){
                    UserRole userRole = new UserRole();
                    userRole.setUserId(userId);
                    userRole.setRoleId(rId);
                    //添加用户角色表
                    userRoleMapper.insert(userRole);
                }
            }
        }
        return "1";
    }

    @Transactional
    @Override
    public String updateUser(User user) {
        if (user==null){
            throw new NotFondException("用户为空");
        }else{
            String userId=user.getId();
            userMapper.updateById(user);
            //删除用户角色表中的数据
            userRoleMapper.delete(new QueryWrapper<UserRole>().eq("user_id",userId));
            //获取角色id
            if (user.getRoleIds()!=null && user.getRoleIds().length>0){
                for (Integer rId:user.getRoleIds()){
                    UserRole userRole = new UserRole();
                    userRole.setUserId(userId);
                    userRole.setRoleId(rId);
                    //添加用户角色表
                    userRoleMapper.insert(userRole);
                }
            }
        }
        return "1";
    }

    @Transactional
    @Override
    public void delUser(String userId) {
        userRoleMapper.delete(new QueryWrapper<UserRole>().eq("user_id",userId));
        userMapper.deleteById(userId);
    }

    /**
     * 批量删除
     * @param userIds
     */
    @Transactional
    @Override
    public boolean delUsers(String userIds[]) {
        if (userIds!=null){
            for (String uid:userIds){
                userRoleMapper.delete(new QueryWrapper<UserRole>().eq("user_id",uid));
            }
            userMapper.deleteBatchIds(Arrays.asList(userIds));
            /*userRoleMapper.delUserRoles(user);
            userMapper.delUsers(user);*/
        }else{
            return false;
        }
        return true;
    }

    /**
     * 业主文件导入逻辑
     * @param uploadFile 上传文件
     * @param addOrUpdate 是否更新
     * @param req request
     * @return
     */
    @Override
    public boolean importFileAddUsers(MultipartFile uploadFile,Boolean addOrUpdate, HttpServletRequest req) {
        try{
            //上传文件 并 将数据上传文件记录表
            String path=FilePathUtil.getSystemAddressServicePath(systemAddressService, "user-uploadFile");
            path= FilePathUtil.pathLast(path);
            UploadFile fileData = FileUploadUtil.uploadPahtFileAndUploadFile(uploadFile, path, req);
            uploadFileMapper.insert(fileData);

            //获取path路径下名为：faleData.getNewName()的文件
            File file=new File(fileData.getFilePath());
            //读取文件信息
            List list = EasyExcelUtil.readExcel(file, UserModel.class);
            List<User> users=new ArrayList();
            //给放到user集合里
            for (Object object:list){
                User user = new User();
                UserModel userModel= (UserModel) object;
                //将userModel的值给user
                BeanUtils.copyProperties(userModel, user);
                user.setCreateTime(new Date());
                //如果addOrUpdate为false说明只是添加，那么就给他的id赋予一个新的uuid，不然就是更新，保留之前的id
                if (!addOrUpdate){
                    user.setId(UUID.randomUUID().toString());
                }
                users.add(user);
            }
            //将信息存放到数据库中
            this.saveOrUpdateBatch(users);
        }catch (Exception e){
            return false;
        }
        return true;
    }

    /**
     * 业主文件导出逻辑
     * @param req request
     * @return
     */
    @Override
    public String downloadUsers(HttpServletRequest req) {
        //文件导出的路径
        String sysPath=FilePathUtil.getSystemAddressServicePath(systemAddressService, "user-exportFile");
        sysPath= FilePathUtil.pathLast(sysPath);
        //获取所有用户数据
        List<User> list=userMapper.selectList(new QueryWrapper());
        //写入excel中
        File file=new File(sysPath+"downloadFile.xlsx");
        EasyExcelUtil.writeExcel(file,list,User.class);
        return FilePathUtil.pathToUrl(file.getPath(),req);
    }

    /**
     * 上传头像
     * @param uploadFile
     * @param req
     * @return
     */
    @Transactional
    @Override
    public String uploadAvatar(MultipartFile uploadFile, HttpServletRequest req) {
        /*
        上传文件 并 将数据上传文件记录表
         */
        //找到要上传的地址
        String path= FilePathUtil.getSystemAddressServicePath(systemAddressService, "user-avatar");
        //完善地址 加"/"
        path= FilePathUtil.pathLast(path);
        //把文件上传
        UploadFile fileData = FileUploadUtil.uploadPahtFileAndUploadFile(uploadFile, path, req);
        //添加到文件记录表中
        uploadFileMapper.insert(fileData);
        //将访问地址返回
        return fileData.getPath();
    }

}
